package com.tihi.treeview;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.tihi.handsuiviewer.R;
import com.tihi.handsuiviewer.UIAnaActivity;
import com.tihi.xml.ViewNode;
import com.tihi.xml.XmlTreeParser;
import com.unnamed.b.atv.model.TreeNode;
import com.unnamed.b.atv.model.TreeNode.TreeNodeClickListener;
import com.unnamed.b.atv.view.AndroidTreeView;

/**
 * Created by Bogdan Melnychuk on 2/12/15.
 */
public class UITreeFrg extends Fragment {
    private AndroidTreeView tView;
    private XmlTreeParser xmlParser;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_default, null, false);
        final ViewGroup containerView = (ViewGroup) rootView.findViewById(R.id.container);

        xmlParser = new XmlTreeParser(getActivity());
        final TreeNode root =  xmlParser.xmlParse(); 
        tView = new AndroidTreeView(getActivity(), root);
//        tView.setDefaultAnimation(true);
        tView.setDefaultContainerStyle(R.style.TreeNodeStyleDivided, true);
        tView.setDefaultNodeClickListener(treeNodeClickListener());
        
        containerView.addView(tView.getView());

        if (savedInstanceState != null) {
            String state = savedInstanceState.getString("tState");
            if (!TextUtils.isEmpty(state)) {
                tView.restoreState(state);
            }
        }
        return rootView;
    }
    
    public XmlTreeParser getXmlParser() {
    	return xmlParser;
    }
    
    /**
     * treeNode 被点击
     * @return
     */
    private TreeNodeClickListener treeNodeClickListener() {
    	return new TreeNodeClickListener() {
			
			@Override
			public void onClick(TreeNode node, Object value) {
				FragmentActivity activity = getActivity();
				if(activity instanceof UIAnaActivity) {
					((UIAnaActivity)activity).onTreeNodeClick(node, value);
				}
			}
		};
    }
    
    /**
     * 展开 treeNode节点
     * 点击屏幕，计算出是哪个最小bounds被点击，则哪个被展开
     * @param treeNode
     */
    public void expandTreeNode(ViewNode viewNode) {
    	TreeNode treeNode = xmlParser.findTreeNodeByViewNode(viewNode);
    	if(treeNode != null) {
    		tView.expandNode(treeNode);
//    		tView.expandLevel(treeNode.getLevel());
    	}
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("tState", tView.getSaveState());
    }
}
